<?php
/**
 * Created by PhpStorm.
 * User: ownfi
 * Date: 2017-04-20
 * Time: 10:31
 */

namespace App\Services\Impl;


use App\Common\Constant\Params;
use App\Models\Merchant;
use App\Models\MerchantTradeLog;
use App\Models\OrderRefund;
use App\Services\IMerchantLogService;
use App\Services\ISystemService;
use DB;

class MerchantLogServiceImpl implements IMerchantLogService
{
    public function orderRefundPayLog(OrderRefund $refund,$amount)
    {
        DB::beginTransaction();
        try{
            $merchant = Merchant::where('me_id',$refund->order->merchant_id)->lockForUpdate()->first();
            $current_balance = $merchant->me_money;
            $new_balance = ($refund->refund_method == Params::REFUND_METHOD_WALLET) ? $current_balance + $amount : $current_balance;

            $model = MerchantTradeLog::where(['type'=>Params::MERCHANT_TRADE_TYPE_REFUND,'order_number_list'=>$refund->id])->first();
            if ($model){
                $ret = $model->update([
                    'balance'=>$new_balance,
                    'ip'=>getip(),
                ]) ? $model : false;
            }else{
                //生成交易流水号
                $trade_number = resolve(ISystemService::class)->genTradeNumber();

                $ret = MerchantTradeLog::create([
                    'trade_number'=>$trade_number,
                    'merchant_id'=>$refund->order->merchant_id,
                    'merchant_name'=>$merchant->me_username,
                    'direction'=>Params::TRADE_DIRECTION_IN,
                    'amount'=>$amount,
                    'type'=>Params::MERCHANT_TRADE_TYPE_REFUND,
                    'source'=>Params::TRADE_SOURCE_SYSTEM,
                    'balance'=>$new_balance,
                    'order_number_list'=>$refund->id,
                    'order_serial_number_list'=>$refund->order_number,
                    'ip'=>getip(),
                    'status'=>Params::TRADE_STATUS_WAITING,
                ]);
            }

            if ($ret){
                DB::commit();
            }else{
                Log::error(sprintf('%s/%s::%s[%d] %s',__NAMESPACE__,__CLASS__,__FUNCTION__,__LINE__-2,'PayAssureFundLog fail'));
                DB::rollBack();
            }

            return $ret;
        }catch (\Exception $e){
            DB::rollBack();
            throw $e;
        }
    }

}